/*
 * @Author: C.
 * @Date: 2023-12-04 13:19:24
 */
import {
  type CSSProperties,
  type InjectionKey,
  computed,
  nextTick,
  provide,
  reactive,
  ref,
} from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useOrderedChildren } from '@tuniao/tnui-vue3-uniapp/hooks'
export type IndexSubPageContext = {
  name: string
  uid: number
  onShow: () => void
  onLoad: () => void
  onHide: () => void
}
export type IndexPageContext = {
  items: IndexSubPageContext[]
  addItem: (item: IndexSubPageContext) => void
  removeItem: (uid: number) => void
}

export const indexPageContextKey: InjectionKey<IndexPageContext> =
  Symbol('indexPageContext')
type Iprops = {
  tabbars: any[]
}
export function useHomePage({ tabbars }: Iprops) {
  const { children, addChild, removeChild } =
    useOrderedChildren<IndexSubPageContext>()

  // 记录每个子页面的状态
  const pageStatus = ref(Array.from({ length: tabbars.length }, () => false))

  // 导航切换事件
  const onTabbarChange = (index: string | number) => {
    // children.value?.[currentTabbarIndex.value as number]?.onHide?.()
    if (!pageStatus.value?.[index as number]) {
      pageStatus.value[index as number] = true
      nextTick(() => {
        children.value?.[index as number]?.onLoad?.()
      })
    }

    children.value?.[index as number]?.onShow?.()
    console.log(children.value?.[index as number])
  }
  // 当前选中的子页面的索引
  const currentTabbarIndex = ref<number>(-1)

  // pageContainer的样式
  const pageContainerStyle = computed<(index: number) => CSSProperties>(() => {
    return (index: number) => {
      const style: CSSProperties = {}

      if (index !== currentTabbarIndex.value) {
        style.display = 'none'
      }

      return style
    }
  })
  onLoad((options: any) => {
    // 获取当前进入的子页面的索引
    const index = Number(options?.index || 0)
    // 设置当前子页面的状态为true
    pageStatus.value[index] = true
    nextTick(() => {
      currentTabbarIndex.value = index
      setTimeout(() => {
        // 执行子页面的onLoad钩子
        children.value?.[index]?.onLoad?.()
      }, 50)
    })
  })
  provide(
    indexPageContextKey,
    reactive({
      items: children,
      addItem: addChild,
      removeItem: removeChild,
    })
  )
  return {
    onTabbarChange,
    pageContainerStyle,
    pageStatus,
    currentTabbarIndex,
  }
}
